<template>
	<div class="image-upload-container">
		<!-- 图片显示区 -->
		<div class="image-list">
			<div v-for="(img, index) in taskImgList" :key="index" class="image-item">
				<img :src="img.data.purl" alt="上传图片" />
				<button class="delete-btn" @click="removeImage(index)">×</button>
			</div>
		</div>

		<!-- 拖拽上传区域 -->
		<div class="upload-area" @dragover.prevent @drop.prevent="handleDrop">
			<input type="file" accept="image/*" @change="handleFileSelect" ref="fileInput" hidden />
			<p>拖拽图片到此处，或 <span @click="triggerFileSelect">点击选择图片</span></p>
		</div>
	</div>
</template>
  
<script>
import { ref } from "vue";
import api from '../api/api.js'
export default {
	setup() {
		// 图片列表
		const taskImgList = ref([]);

		

		// 处理文件选择
		const handleFileSelect = async (event) => {
			const file = event.target.files[0];
			if (file) {
				await uploadImage(file);
			}
			event.target.value = ""; // 清空选择器的值以支持重复选择同一文件
		};

		// 处理拖拽
		const handleDrop = async (event) => {
			const file = event.dataTransfer.files[0];
			if (file) {
				await uploadImage(file);
			}
		};

		// 上传图片
		const uploadImage = async (file) => {
			try {
				const data = new FormData()
				data.append('file', file)
				data.append('aid', 2134)
				const result = await api.uploadImgApi(data);
				taskImgList.value.push(result);
			} catch (error) {
				console.error("上传失败", error);
			}
		};

		// 删除图片
		const removeImage = (index) => {
			taskImgList.value.splice(index, 1);
		};

		// 触发文件选择
		const fileInput = ref(null);
		const triggerFileSelect = () => {
			fileInput.value.click();
		};

		return {
			taskImgList,
			handleFileSelect,
			handleDrop,
			removeImage,
			triggerFileSelect,
			fileInput,
		};
	},
};
</script>
  
<style scoped>
.image-upload-container {
	width: 100%;
	margin: 20px auto;
	text-align: center;
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-bottom: 20px;
	justify-content: center;
}

.image-item {
	position: relative;
	width: 100px;
	height: 100px;
	overflow: hidden;
	border: 1px solid #ddd;
	border-radius: 5px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.image-item img {
	max-width: 100%;
	max-height: 100%;
	object-fit: cover;
}

.delete-btn {
	position: absolute;
	top: 5px;
	right: 5px;
	background: rgba(255, 0, 0, 0.8);
	color: white;
	border: none;
	border-radius: 50%;
	width: 20px;
	height: 20px;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
}

.delete-btn:hover {
	background: red;
}

.upload-area {
	border: 2px dashed #007bff;
	border-radius: 10px;
	padding: 20px;
	color: #666;
	cursor: pointer;
	transition: border-color 0.3s;
}

.upload-area:hover {
	border-color: #0056b3;
}

.upload-area span {
	color: #007bff;
	text-decoration: underline;
	cursor: pointer;
}
</style>
  